package com.example.studentdemo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.studentdemo.constant.RoleConstant;
import com.example.studentdemo.entity.Account;
import com.example.studentdemo.entity.Teacher;
import com.example.studentdemo.exception.CustomerException;
import com.example.studentdemo.mapper.TeacherMapper;
import com.example.studentdemo.service.TeacherService;
import com.example.studentdemo.utils.PasswordUtils;
import com.example.studentdemo.utils.TokenUtils;
import com.example.studentdemo.utils.UidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Resource
    TeacherMapper teacherMapper;

    @Override
    public List<Teacher> selectAll(Teacher teacher) {
        return teacherMapper.selectAll(teacher);
    }

    @Override
    public Teacher selectByUsername(String username) {
        return teacherMapper.selectByUsername(username);
    }

    @Override
    public void add(Teacher teacher) {
        Teacher dbTeacher = teacherMapper.selectByUsername(teacher.getUsername());
        if (dbTeacher != null) {
            throw new CustomerException("账号重复了");
        }

        teacher.setRole(RoleConstant.TEACHER_ROLE);
        teacher.setUuid(UidUtils.generateUid());
        if (!StrUtil.isNotBlank(teacher.getPassword())) {
            teacher.setPassword(PasswordUtils.encryptPassword("teacher"));
        }else {
            teacher.setPassword(PasswordUtils.encryptPassword(teacher.getPassword()));
        }
        teacherMapper.insert(teacher);
    }

    @Override
    public void register(Teacher teacher) {
        // 检查账号是否存在
        Teacher dbTeacher = teacherMapper.selectByUsername(teacher.getUsername());
        if (dbTeacher != null) {
            throw new CustomerException("账号重复了");
        }
        // 加密密码
        teacher.setPassword(PasswordUtils.encryptPassword(teacher.getPassword()));
        // 设置角色
        teacher.setRole("TEACHER");
        // 生成UUID
        teacher.setUuid(UidUtils.generateUid());
        // 插入数据库
        teacherMapper.insert(teacher);
    }

    @Override
    public void update(Teacher teacher) {
        teacherMapper.updateById(teacher);
    }

    @Override
    public PageInfo<Teacher> selectPage(Integer pageNum, Integer pageSize, Teacher teacher) {
        PageHelper.startPage(pageNum, pageSize);
        List<Teacher> teacherList = teacherMapper.selectAll(teacher);
        return PageInfo.of(teacherList);
    }

    @Override
    public void deleteById(Integer id) {
        teacherMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<Teacher> teacherList) {
        for (Teacher teacher : teacherList) {
            this.deleteById(teacher.getId());
        }
    }

    @Override
    public Teacher selectById(Integer userId) {
        return teacherMapper.selectById(userId);
    }

    @Override
    public Teacher login(Account account) {
        // 验证账号是否存在
        Teacher dbTeacher = teacherMapper.selectByUsername(account.getUsername());
        if (dbTeacher == null) {
            throw new CustomerException("账号不存在");
        }
        // 验证密码是否正确
        if (!PasswordUtils.matchesPassword(account.getPassword(), dbTeacher.getPassword())) {
            throw new CustomerException("账号或密码错误");
        }
        // 获取设备ID（从account中获取或生成默认值）
        String deviceId = account.getDeviceId();
        if (StrUtil.isBlank(deviceId)) {
            deviceId = "default-device";
        }
        // 创建token并返回给前端
        String token = TokenUtils.createToken(String.valueOf(dbTeacher.getId()), "TEACHER", dbTeacher.getPassword(), deviceId);
        dbTeacher.setToken(token);
        return dbTeacher;
    }

    @Override
    public void updatePassword(Account account) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null) {
            if (!PasswordUtils.matchesPassword(account.getPassword(), currentUser.getPassword())) {
                throw new CustomerException("500", "原密码输入错误");
            }
            Teacher dbTeacher = teacherMapper.selectById(currentUser.getId());
            // 密码更新后，注销该用户的所有登录会话
            TokenUtils.logoutAll(String.valueOf(dbTeacher.getId()), "TEACHER");
            dbTeacher.setPassword(PasswordUtils.encryptPassword(account.getNewPassword()));
            teacherMapper.updateById(dbTeacher);
        }
    }
}
